<template>
  <MenuPage 
      :data="roleList" 
      :columns="roleCol" 
      :page.sync="rolePage" 
      :size.sync="rolePageSize" 
      :total="roleCount"
      :loading="tableLoading"
      @queryFun="queryRoleList">
    <template slot="search">
      <Button ghost style="height: 32px;margin-left: 15px" type="primary" class="md-add-jh" @click="creatroleBtn">创建{{
        pageTitle }}</Button>
      <div style="height: 32px;line-height: 32px;;margin-left: 15px"></div>
      <Input v-model.trim="searchExpGroupInput" placeholder="角色名称" clearable @on-change="searchExpGroup"
        style="width: 180px;margin-left: 15px" />
      <Input v-model.trim="searchNickname" placeholder="成员名称" clearable @on-change="searchExpGroup"
        style="width: 180px;margin-left: 15px" />
      <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refreshExpGroup()">
        <i class="el-icon-refresh-right" />
      </Button>
    </template>
    <!-- 创建/修改 角色组-->
    <Modal v-model="roleModal" :mask-closable="false" width="500" :footer-hide="true" @on-visible-change="visibleChange"
      :title="groupText">
      <Form ref="formItem" :model="formItem" :rules="formItemRuleValidate" :label-width="100">
        <FormItem label="名称" prop="name">
          <Input v-model.trim="formItem.name" placeholder="名称"></Input>
        </FormItem>
        <FormItem label="岗位角色等级" prop="level">
          <Select filterable v-model="formItem.level">
            <Option v-for="item in gradeList" :value="item.value" :key="item.value">{{
              item.label
              }}</Option>
          </Select>
        </FormItem>
        <FormItem label="描述" prop="description">
          <Input v-model.trim="formItem.description" type="textarea" :maxlength="200"
            :autosize="{ minRows: 2, maxRows: 5 }" placeholder="描述"></Input>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="formBtn()">确定</Button>
          <Button @click="roleHandleReset('formItem')" style="margin-left: 8px">重置</Button>
        </FormItem>
      </Form>
    </Modal>
  </MenuPage>
</template>
<script>
  import $ from 'jquery';
  import encryption from '@/libs/encryption.js';
  import {
    getGroupHasUsers,
    creatGroup,
    reGroup,
    delGroup,
    creatInvaita,
    checkApply,
    refuseApply,
    resetPwd,
    getPwdBlackList,
    exportUsers,
    deleteListUser,
    deleteGroups
  } from '@/api/company.js';
  import { queryRole, delRole, addRole, modRole } from '@/api/role.js';
  import { sendToUser } from '@/api/boardcast_new.js';
  import { debounce } from '@/libs/utils';
  import pageTitle from '@/mixin/pageTitle';
  export default {
    components: {},
    mixins: [pageTitle],
    data() {
      let regUsername = /^[0-9A-Za-z_]{5,18}$/; // 账号是数字 字母 或者下划线的组合
      let regPasswd = /^(?!.*\s)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{8,16}$/; // 密码必须包含大小写字母、数字和特殊字符，长度为8—16
      const validateUsername = (rule, value, callback) => {
        if (regUsername.test(value)) {
          callback();
        } else {
          callback(new Error('请输入长度为5-18位的账号,可以使用数字、字母或者下划线'));
        }
      };
      const validatePass = (rule, value, callback) => {
        if (regPasswd.test(value)) {
          callback();
        } else {
          callback(new Error('密码必须包含大写字母，小写字母，数字和特殊字符，长度为8-16位'));
        }
      };
      const validateNickname = (rule, value, callback) => {
        if (value.length < 1) {
          callback(new Error('昵称不能为空'));
        } else if (value.length > 32) {
          callback(new Error('昵称长度不能超过32位'));
        } else {
          callback();
        }
      };
      const validateGroupname = (rule, value, callback) => {
        if (value.length < 1) {
          callback(new Error('角色组名称不能为空'));
        } else if (value.length > 32) {
          callback(new Error('角色组名称长度不能超过32'));
        } else if (value.indexOf('@') > -1) {
          callback(new Error('角色组名称不能使用@符'));
        } else {
          callback();
        }
      };
      return {
        roleList: [],
        tableLoading:true,
        rolePage: 1,
        rolePageSize: 12,
        roleCount: 0,
        /////////////////////////////
        userForm: {
          id: ''
        },
        newPassword: {
          Password: ''
        },
        showChangePass: false,
        // 用户信息
        USER_ID: '',
        isRootDesigner: '',
        // 页面设置
        fullHeight: document.documentElement.clientHeight,
        fullWidth: document.documentElement.clientWidth,
        setTableHei: 'auto',
        // 表格显示
        showroleData: false,
        showroleImg: false,
        // 单位
        // 获取所有的课件用户组
        allGroupList: [],
        // 课件用户组数据
        ExperimentalUserGroupList: [],
        ExperimentalUserGroupCol: [],
        isCanClickReviceAndDelBtn: false,
        experGroupLoading: true,
        expGroupVisibility: '',
        filterExpGroup: 'all',
        expGroupCount: 0,
        groupPage: 1,
        groupPageSize: 12,
        roleGroupName: '',
        searchExpGroupInput: '',
        searchNickname: '',
        // 创建/修改实验组
        groupText: '',
        isCreate: true,
        roleModal: false,
        formItem: {
          name: '',
          description: '',
          level: '1'
        },
        //岗位角色等级
        gradeList: [
          {
            value: '1',
            label: '初级'
          },
          {
            value: '2',
            label: '中级'
          },
          {
            value: '3',
            label: '高级'
          }
        ],
        formItemRuleValidate: {
          name: [
            { required: true, validator: validateGroupname, trigger: 'change' },
            { type: 'string', min: 1, max: 32, message: '请选择能见度', trigger: 'change' }
          ],
          visibility: [{ required: true, message: '请选择能见度 ', trigger: 'change' }],
          description: [{ max: 200, message: '说明不能超过200个字母', trigger: 'change' }],
          level: [
            {
              required: true,
              message: '岗位角色等级不能为空',
              trigger: 'blur'
            }
          ]
        },
        roleId: '',
        // 邀请码
        // 密码黑名单
        pwdBlackList: [],
        // 重置密码img
        // resetImg:require('../../assets/project/resetPwd-h.png'),
        invitaIcon: require('../../assets/project/invita-h.png'),
        memsIcon: require('../../assets/project/mems-h.png'),
        //导入报告
        uploadAction: '/api/identity/company/users/import',
        uploadGroupAction: '/api/identity/experimenterGroups/import',
        uploadHeader: {
          Authorization: localStorage.token,
          Accept: '*/*'
        },
        uploaderror: false,
        filename: '',
        selectAllGroup: false,
        selectGroups: [],
        isRetainer: true,
        roleCol: [
          // {
          //   type: 'selection',
          //   width: 60,
          //   align: 'left'
          // },
          {
            title: '角色名称',
            key: 'name',
            placement: 'top-left',
            minWidth: 100,
            tooltip: true
          },
          {
            title: '成员',
            key: 'users',
            tooltip: true,
            minWidth: 100,
            render: (h, params) => {
              return h(
                'span',
                {
                  style: {
                    display: 'inline'
                  }
                },
                params.row.users.length > 0
                  ? params.row.users.map((user) => user.userName).join(',')
                  : '-'
              );
            }
          },

          { title: '描述', key: 'description', tooltip: true, minWidth: 100 },
          {
            title: '创建者',
            key: 'creatorName',
            tooltip: true,
            minWidth: 100
          },
          {
              title: '创建时间',
              key: 'created',
              tooltip: true,
              width: 200
          },
          {
            title: '操作',
            width: 180,
            placement: 'top-right',
            slot: 'action',
            opList: [
              {
                txt: '修改',
                disabled: (data) => {
                  return this.setIsClick(data);
                },
                on: {
                  click: (data) => {
                    this.madifyGroup(data);
                  }
                }
              },
              {
                txt: '成员管理',
                // disabled: (data) => {
                //     return !this.setIsClick(data);
                // },
                on: {
                  click: (data) => {
                    this.membersManage(data)
                  }
                }
              },
              {
                txt: '删除',
                tooltip: true,
                type: 'delete',
                title: '你确定要删除吗?',
                on: {
                  click: (data) => {
                    this.delRole(data);
                  }
                },
                disabled: (data) => {
                  return this.setIsClick(data);
                }
              }
            ]
          }
        ],
      };
    },
    created() {
      // 获取用户id
      let November = sessionStorage.getItem('November');
      November = JSON.parse(encryption.SelfUseDecrypt(November));
      this.USER_ID = November.userId;
      this.isRootDesigner = November.isRootDesigner;
      this.userName = November.userName;
      this.isRetainer = sessionStorage.getItem('isRetainer') === 'true';
      console.log(
        '%c [ this.isRetainer ]',
        'font-size:13px; background:pink; color:#bf2c9f;',
        this.isRetainer
      );
    },
    mounted() {
      //          let getPage = this.$route.query.page?parseInt(this.$route.query.page):1
      //          this.groupPage = getPage
      this.queryRoleList()
      this.isRetainer = sessionStorage.getItem('isRetainer') === 'true';
      console.log(
        '%c [ this.isRetainer ]',
        'font-size:13px; background:pink; color:#bf2c9f;',
        this.isRetainer
      );
    },
    methods: {
      visibleChange(type) {
        if (!type) {
          this.$refs.formItem.resetFields();
        }
      },
      // 设置高度
      setStyle() {
        window.fullHeight = document.documentElement.clientHeight;
        window.fullWidth = document.documentElement.clientWidth;
        this.fullHeight = window.fullHeight;
        this.fullWidth = window.fullWidth;
        this.setTableHei = this.fullHeight - 197 + 'px';
        let num = this.fullHeight - 197;
        this.groupPageSize = Math.floor(num / 96);
        this.queryRoleList()
      },
      queryRoleList: debounce(function (val) {
        this.tableLoading = true;
        let params = {
          pageIndex: this.rolePage,
          pageSize: this.rolePageSize,
          userName: this.searchNickname,
          name: this.roleGroupName
        };
        queryRole(params).then((res) => {
          if ((res.data.code = 1)) {
            this.roleList = res.data.data.items;
            this.roleCount = res.data.data.total;
            if (this.roleList.length > 0) {
              this.showroleData = true;
              this.showroleImg = false;
            } else {
              this.showroleData = false;
              this.showroleImg = true;
            }
          }
          this.tableLoading = false;
        }).finally(() => {
          this.tableLoading = false;
        });
      }, 500),
      // 过滤
      roleOnChange(val) {
        this.rolePage = val;
        this.queryRoleList();
      },
      searchExpGroup(val) {
        this.groupPage = 1;
        val = this.searchExpGroupInput;
        this.roleGroupName = val;
        this.queryRoleList();
      },
      searchCreatedByMe(val) {
        this.groupPage = 1;
        this.queryRoleList();
      },
      refreshExpGroup() {
        this.selectGroups = []; //清空
        this.groupPage = 1;
        this.filterExpGroup = 'all';
        this.roleGroupName = '';
        this.searchExpGroupInput = '';
        this.searchNickname = '';
        this.queryRoleList();
      },
      isCanClick(creator) {
        if (this.isRootDesigner || this.USER_ID === creator) {
          return false;
        } else {
          return true;
        }
      },
      // 创建
      creatroleBtn() {
        this.isCreate = true;
        this.roleModal = true;
        this.groupText = `创建${this.pageTitle}`;
        this.formItem.name = '';
        this.formItem.description = '';
      },
      // 修改
      madifyGroup(row) {
        this.isCreate = false;
        this.roleModal = true;
        this.groupText = `修改${this.pageTitle}`;
        this.roleId = row.id;
        this.formItem.name = row.name;
        this.formItem.description = row.description;
        this.formItem.level = row.level + '';
      },
      // 创建/修改
      formBtn() {
        if (this.isCreate) {
          this.addRole();
        } else {
          this.modRole();
        }
      },
      addRole() {
        this.$refs['formItem'].validate((valid) => {
          if (valid) {
            addRole(this.formItem).then((res) => {
              console.log(res);
              if (res.data.code == 1) {
                this.$Message.success(res.data.message);
              } else {
                this.$Message.warning(res.data.message);
              }
              this.roleModal = false;
              this.queryRoleList();
            });
          } else {
            this.$Message.error('请完善信息！');
          }
        });
      },
      delRole(item) {
        delRole(item.id).then((res) => {
          console.log(res);
          if (res.data.code == 1) {
            this.$Message.success(res.data.message);
          } else {
            this.$Message.warning(res.data.message);
          }
          this.queryRoleList();
        });
      },
      modRole(name) {
        this.$refs['formItem'].validate((valid) => {
          if (valid) {
            modRole(this.formItem, this.roleId).then((res) => {
              if (res.data.code == 1) {
                this.$Message.success(res.data.message);
              } else {
                this.$Message.warning(res.data.message);
              }
              this.queryRoleList();
              this.roleModal = false;
            });
          } else {
            this.$Message.error('请完善信息！');
          }
        });
      },
      roleHandleReset(name) {
        this.$refs[name].resetFields();
      },

      // 成员管理
      membersManage(row) {
        this.$router.push({
          name: 'creatRoleGroup',
          query: {
            id: row.id,
            name: row.name,
            page: this.rolePage,
            creator: row.creator
          }
        });
      },
      handleGroupIndex(key) {
        return (this.groupPage - 1) * this.groupPageSize + key + 1;
      },
      // 是否可以删除
      setIsClick(item) {
        if (item.creator !== this.USER_ID) {
          return true //{ 'pointer-events': 'none' };
        }
      },
      setImgSrc(item) {
        if (item.creator !== this.USER_ID) {
          return require('../../assets/project/modifys.png');
        } else {
          return require('../../assets/project/modifys-h.png');
        }
      },
      setDelImgSrc(item) {
        if (item.creator !== this.USER_ID || item.role === 'leader') {
          return require('../../assets/project/delNote-d.png');
        } else {
          return require('../../assets/project/delNote-h.png');
        }
      },
      checkSingleGroup(e, group) {
        if (e && !this.selectGroups.map((group) => group.id).includes(group.id)) {
          this.selectGroups.push(group);
        } else if (!e && this.selectGroups.map((group) => group.id).includes(group.id)) {
          let index = this.selectGroups.findIndex((item) => group.id == item.id);
          this.selectGroups.splice(index, 1);
        }
        this.$set(group, '_checked', e);
        if (
          this.ExperimentalUserGroupList.length > 0 &&
          this.ExperimentalUserGroupList.every((group) => group._checked === true)
        ) {
          this.selectAllGroup = true;
        } else {
          this.selectAllGroup = false;
        }
      },
      //发送公告
      sendToUser(row, type) {
        let params = {
          content:
            type == 'agree'
              ? `[${this.userName}]已同意你加入实验组[${this.applyGroupName}]`
              : `[${this.userName}]已拒绝你加入实验组[${this.applyGroupName}]`,
          id: '',
          status: 0,
          title: '',
          type: 1,
          users: [
            {
              userIds: [row.userId]
            }
          ]
        };
        sendToUser(params)
          .then((data) => {
            if (data.code == 1) {
              //this.$Message.info('发送成功');
            } else {
              //this.$Message.error(data.message);
              setTimeout(() => {
                this.sendToUser(row, type);
              }, 2000);
            }
          })
          .catch((error) => {
            console.log(error);
            //this.$Message.error("公告发送失败");
          });
      }
    }
  };
</script>
<style scoped>
</style>